package com.five.welcome.controller;

import com.five.welcome.config.websockethandler.WebSocketServer;
import com.five.welcome.result.Result;
import com.five.welcome.utils.QRCodeGenerator;
import com.google.zxing.WriterException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@CrossOrigin
@Slf4j
@RequestMapping
public class QRController {

    @Autowired
    private WebSocketServer webSocketServer;

    //生成二维码
    @GetMapping("/generateQRCode")
    public String generateQRCode(String textOrUrl) {
        String base64 = "";
        try {
            base64 = QRCodeGenerator.generateQRCodeImage(textOrUrl);
        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        log.info("生成了二维码");
        //返回base64
        return "data:image/png;base64," + base64;
    }


    //二维码被扫描后调用
    @GetMapping("/afterScan")
    public String AfterScanQR() {
        log.info("二维码已被扫描...");
        //向前端发送消息
        webSocketServer.sendMessage("/reportAll/messageCollect", "qr");
        //返回一个静态页面
        return "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>欢迎您的到来!</title>\n" +
                "    <style>\n" +
                "        .top{\n" +
                "            height: 100px;\n" +
                "            width: 100%;\n" +
                "            background-color: gray;\n" +
                "        }\n" +
                "        .main{\n" +
                "            text-align: center;\n" +
                "            color: blueviolet;\n" +
                "            font-size: larger;\n" +
                "        }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body>\n" +
                "<div class=\"top\"></div>\n" +
                "<div class=\"main\"><h1>扫码报到成功</h1></div>\n" +
                "</body>\n" +
                "</html>";
    }
}
